package com.mine.frame.mylandemo.ui.autorail

import android.annotation.SuppressLint
import android.app.Service
import android.content.ComponentName
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.text.Editable
import com.blankj.utilcode.util.ClickUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.ServiceUtils
import com.blankj.utilcode.util.SnackbarUtils
import com.mine.frame.common.base.BaseActivity
import com.mine.frame.mylandemo.R
import com.mine.frame.mylandemo.adapter.forick.Panel3In1Adapter
import com.mine.frame.mylandemo.entity.forick.ControlBean
import com.mine.frame.mylandemo.mvp.iview.ICurtainHoneycomb
import com.mine.frame.mylandemo.mvp.presenter.CurtainHoneycombPresenter
import com.swallowsonny.convertextlibrary.toHexString
import com.third.device.mg.serialport.MGSerialPort
import com.third.device.mg.serialport.listener.MGNettyConnectListener
import com.third.device.mg.serialport.service.MGSocketService
import com.third.device.mg.serialport.utils.to2ByteL
import kotlinx.android.synthetic.main.atv_forick_panel_3in1.*
import kotlinx.android.synthetic.main.layout_connect.*

/**
 * @Date 2022/1/20
 * Description:
 * 波特率：2400
 */
@SuppressLint("SetTextI18n")
public class CurtainHoneycombAtv : BaseActivity<ICurtainHoneycomb, CurtainHoneycombPresenter>(),
    ICurtainHoneycomb, MGNettyConnectListener {
    /*当前连接的IP地址 和 端口号*/
    private var ipStr = ""
    private var port = 61233
    /*设备地址*/
    private val devAddress = 1
    private var readHLR :ByteArray? = null

    private val mAdapter by lazy { Panel3In1Adapter() }

    override fun initLayoutId(): Int = R.layout.atv_forick_panel_3in1

    override fun initPresenter(): CurtainHoneycombPresenter = CurtainHoneycombPresenter(this)



    private val serviceConnect: ServiceConnection by lazy {
        object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                SnackbarUtils.with(tvInfo).setMessage("正在连接服务器...").showSuccess()
                MGSocketService.get().setListener(this@CurtainHoneycombAtv)
            }

            override fun onServiceDisconnected(name: ComponentName?) {
            }
        }
    }

    override fun initLayoutAfter(savedInstanceState: Bundle?) {
        ipStr = intent?.getStringExtra("sel-ip").toString()
        edtIP.text = Editable.Factory.getInstance().newEditable(ipStr)
        connectAndDisconnect()
        initRecycler()
        mPresenter.createControlData()
    }


    /**
     * 连接和取消连接
     */
    private fun connectAndDisconnect() {
        ClickUtils.applySingleDebouncing(arrayOf(btnConnect ,btnDisconnect)){
            when(it.id){
                R.id.btnConnect ->{
                    KeyboardUtils.hideSoftInput(this)
                    if (edtIP.text.isNullOrEmpty()){
                        SnackbarUtils.with(edtIP).setMessage("请输入IP地址").showWarning()
                        return@applySingleDebouncing
                    }else{
                        ipStr = edtIP.text.toString()
                    }


                    if (edtPort.text.isNullOrEmpty()){
                        SnackbarUtils.with(edtIP).setMessage("请输入端口号").showWarning()
                        return@applySingleDebouncing
                    }else{
                        port =edtPort.text.toString().toInt()
                        if (port < 1 || port > 65535){
                            SnackbarUtils.with(edtIP).setMessage("端口号异常(1,65535)").showWarning()
                            return@applySingleDebouncing
                        }
                    }
                    if (ipStr.isEmpty()){
                        SnackbarUtils.with(edtIP).setMessage("IP地址异常").showError()
                        return@applySingleDebouncing
                    }

                    initSocket()
                }
                R.id.btnDisconnect ->{
                    MGSocketService.get().disconnect(ipStr,port)
                }
            }
        }

    }


    override fun onStart() {
        super.onStart()
        if (!MGSocketService.get().isBind){
            ServiceUtils.bindService(MGSocketService::class.java, serviceConnect, Service.BIND_AUTO_CREATE)
        }
    }


    /**
     * 创建Socket连接
     */
    private fun initSocket(){
        MGSocketService.get().connectNetty(ipStr ,port)
    }


    /**
     * 更新指示器
     */
    private fun updateIndicator(connect:Boolean){
        val resId = if (connect){
            R.drawable.blue_circle
        }else{
            R.drawable.red_circle
        }
        viewIndicator.setBackgroundResource(resId)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (MGSocketService.get().isBind){
            ServiceUtils.unbindService(serviceConnect)
        }
    }

    private fun initRecycler(){
        mRecycler.adapter = mAdapter
        mAdapter.setOnItemClickListener{ _, _, position ->
            val controlBean = mAdapter.data[position]
            if (!controlBean.isHeader){
                controlBean.command?.let {
                    //MGSocketService.get().write(ipStr ,port ,it)
                    MGSocketService.get().write(ipStr ,port ,it)
                }?:let {
                    SnackbarUtils.with(btnConnect).setMessage("指令未空").showWarning(true)
                }
            }
        }
        mAdapter.addChildClickViewIds(R.id.btnGet)
        mAdapter.setOnItemChildClickListener{_, _, position ->
            val controlBean = mAdapter.data[position]
            controlBean.readHLR?.let {
                this.readHLR = it
                val command = MGSerialPort.instance.getForick().panel3In1().getReadHLRCommand(getAddress(),it)
                //MGSocketService.get().write(ipStr ,port ,command)
                MGSocketService.get().write(ipStr ,port ,command)
                showReadMsg("--")
            }
        }
    }


    override fun getAddress(): Byte = devAddress.to2ByteL()[0]

    override fun initControlList(data: MutableList<ControlBean>) {
        mAdapter.setList(data)
    }

    override fun getReadHLRAddress(): ByteArray? = readHLR

    override fun showReadMsg(string: String) {
        tvRead.text = string
    }

    override fun connectBack(ip: String, port: Int) {
        updateIndicator(true)
    }

    override fun disconnectBack(ip: String, port: Int) {
        updateIndicator(false)
    }


    override fun readBack(ip: String, port: Int, result: ByteArray) {
        SnackbarUtils.with(btnConnect).setMessage("收到消息").showSuccess(true)
        tvInfo.text = "接收:${result.toHexString(true)}"
    }

    override fun writeBack(ip: String, port: Int, successful:Boolean, data:ByteArray) {
        if (successful){
            SnackbarUtils.with(btnConnect).setMessage("发送成功").showSuccess(true)
        }else{
            SnackbarUtils.with(btnConnect).setMessage("发送失败").showError(true)
        }

    }

    override fun errorBack(ip: String, port: Int, error: Throwable) {

        error.message?.let {
            showErr(it)
        }
    }
}